/**
 * 
 */
package fpt.pits.dao;

import java.sql.SQLException;

import fpt.pits.dto.UserInfo;
import fpt.pits.util.Connection;

/**
 * @author yoyosakura
 *
 */
public class LoginInfoDAO {
    /**
     * get the information of user by username and password
     * @param username
     * @param password
     * @return
     */
    public UserInfo get(String username, String password) {
        UserInfo userInfo = null;
        java.sql.Connection cn = null;
        java.sql.PreparedStatement ps = null;
        java.sql.ResultSet rs = null;
        String query = null;
        try {
            query = "SELECT * " +
            		"FROM `user` u " +
            		"WHERE u.UserName = ? and u.Password = ?";
            cn = Connection.getConnection();
            ps = cn.prepareStatement(query);
            ps.setString(1, username);
            ps.setString(2, password);
            rs = ps.executeQuery();
            while (rs.next()) {
                if (rs.getByte("IsDeleted") == 1) {
                    return null;
                } else {
                    userInfo = new UserInfo();
                    userInfo.setEmpID(rs.getInt("EmpID"));
                    userInfo.setUsername(rs.getString("UserName"));
                    userInfo.setPassword(rs.getString("Password"));
                    userInfo.setRole(rs.getString("Role"));
                    userInfo.setLastLogin(rs.getString("LastLogin"));
                    userInfo.setIsDeleted(rs.getByte("IsDeleted"));
                }
            }
        } catch (Exception e) {
            System.err.println("Error: Get data from database " + e.getMessage());
        } finally {
            try {
                if (rs != null) {
                    rs.close();
                }
                if (ps != null) {
                    ps.close();
                }
                if (cn != null) {
                    cn.close();
                }
            } catch (SQLException sqle) {
                System.out.println("Error: No close connection " + sqle.getMessage());
            }
        }
        return userInfo;
    }
}
